"""
自定义中间件
"""
import logging
import traceback

from django.contrib.auth.backends import ModelBackend
from django.utils.deprecation import MiddlewareMixin
import jwt
from rest_framework_jwt.utils import jwt_decode_handler

from account.common import get_resource_list
from account.models import Account

logger = logging.getLogger('log')


class AuthMiddleware(MiddlewareMixin):
    """
    验证token中间件
    """

    def process_request(self, request):
        """
        视图执行前
        """
        token = request.headers.get('Authorization')
        if token:
            token = token.replace('Bearer ', '')
            try:
                jwt_token = jwt_decode_handler(token)
                user = Account.objects.get(id=jwt_token.get('user_id'))
                request.user = user
                return
            except:
                return False
        return


class AuthorBackend(ModelBackend):
    """
    重写登录注册的密码验证
    """

    def authenticate(self, request, username=None, password=None, **kwargs):
        user = Account.objects.get(username=username)
        logger.error('AuthorBackend error:{}'.format(locals()))
        if user and user.check_password(password):
            return user
        return None


def jwt_response_payload_handler(token, user, request):
    if user is not None:
        if user.is_active:
            resource_list = get_resource_list(user)
            superuser = str(user.is_superuser)
            return {'code': 200, 'data': {'resource_list': resource_list, 'superuser': superuser, 'token': token}}
        return {'code': 500, 'message': '用户已经被禁用'}
    # 否则就是用户名、密码有误
    return {'code': 406, 'message': '用户名或者密码错误'}
